
<template>
	<div class="app-container" v-loading="loading">
	
		<div class="search-container app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="6">
						<el-date-picker
							v-model="queryParams.date"
							style="width: 100%"
							type="daterange"
							clearable
							unlink-panels
							range-separator="To"
							start-placeholder="开始日期"
							end-placeholder="截止日期"
							:shortcuts="shortcuts"
						/>
					</el-col>
					<el-col :span="4">
						<el-tree-select
								placeholder="请选择所属公司"
								v-model="queryParams.otherid"
								:data="baseConfigStore.newExDepartmentList"
								:render-after-expand="false"
								:default-expand-all="true"
								clearable
								check-strictly
								:props="{
									label: 'name',
									children: 'children',
									value: 'id',
								}"
								@current-change="companyChange"
						/>
						
					</el-col>
				<!-- 	<el-col :span="3">
						<el-input v-model="queryParams.name" clearable placeholder="请输入姓名" @keyup.enter="handleQuery" />
					</el-col> -->
					<el-col :span="6" >
						<el-button  :loading="loading"  type="primary" @click="handleQuery"><template
							#icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn
				 class="filtBox"
				 @handleRefresh="resetQuery()"
				 @handleLaunch="filterMore()"
				 :launch="true"
				 :showMore="showMore"
				 :strtype="strtype"></FilterColumn>
				
			</div>	
			<div v-if="showMore" class="index_header_input">
				<el-row :gutter="12" style="width:100%">
					<el-col :span="4">
						<el-tree-select
						style="width:100%"
								placeholder="请选择所属部门"
								v-model="queryParams.department_id"
								:data="departmentOptions"
								:render-after-expand="false"
								:default-expand-all="true"
								check-strictly
								:props="{
									label: 'name',
									children: 'children',
									value: 'id',
									disabled: function(data, node) {
									  if(data.type == 1){
										return true;
									  }else{
										return false;
									  }
									}
								}"
							/>
					</el-col>
					<el-col :span="4">
						<el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery"/>
					</el-col>
				</el-row>
			</div>
		</div>
		
		<el-card shadow="never">
			<div class="action-row">
				<el-button v-hasPerm="['KaoqinDownload']" type="primary" @click="downloadTemplate()" plain><template #icon><i-ep-download /></template>下载模板</el-button>
				<el-button v-hasPerm="['KaoqinImport']" type="primary" @click="openImportDialog()" plain><template #icon><i-ep-upload /></template>导入考勤</el-button>
			</div>
			<el-table ref="dataTableRef" 
				v-loading="loading" 
				:data="tableData" 
				align="center" 
				:show-overflow-tooltip="true"
				:scrollbar-always-on="true"
				border>
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column 
						:label="item.label" 
						:align="item.align" 
						:prop="item.prop" 
						:width="item.width"
						:min-width="item.minwidth">
						<template v-if="item.label == '所属公司'" #default="scope">
						  	{{ scope.row.company }}				
						</template>	
						<template v-if="item.label == '所属部门'" #default="scope">			
						 	{{ scope.row.department }}
						</template>	
						<template v-if="item.label == '出勤'" #default="scope">
						  	<el-link type="success" @click="showLog(1,scope.row.log)">{{ scope.row.chuqin }}天</el-link>
						</template>	
						<template v-if="item.label == '事假'" #default="scope">	
						  	<el-link type="success" @click="showLog(7,scope.row.log)">{{ scope.row.shijia }}天</el-link>
						</template>	
						<template v-if="item.label == '病假'" #default="scope">
						  	<el-link type="success" @click="showLog(6,scope.row.log)">{{ scope.row.bingjia }}天</el-link>			
						</template>	
						<template v-if="item.label == '年假'" #default="scope">
							<el-link type="success" @click="showLog(8,scope.row.log)">{{ scope.row.nianjia }}天</el-link>
						</template>	
						<template v-if="item.label == '旷工'" #default="scope">
							<el-link type="danger" @click="showLog(4,scope.row.log)">{{ scope.row.kuanggong }}天</el-link>
						</template>
						<template v-if="item.label == '加班'" #default="scope">
							<el-link type="success" @click="showLog(9,scope.row.log)">{{ scope.row.jiaban }}小时</el-link>
						</template>
					</el-table-column>
				</template>
				
				
			
			</el-table>
		</el-card>

		<!-- 打卡记录弹框 -->
		<el-dialog v-model="logDialog.visible" :title="logDialog.title" width="600px" @close="closeLogDialog">
			<el-table :data="logList" align="center"  border>
				<el-table-column label="日期" align="center" prop="work_date"/>
				<el-table-column v-if="logDialog.title != '加班记录'" label="上午" align="center" prop="shangwu">
					<template #default="scope">
						<el-text :type="scope.row.shangwu_class">{{ scope.row.shangwu }}</el-text>
					</template>
				</el-table-column>

				<el-table-column v-if="logDialog.title != '加班记录'" label="下午" align="center" prop="xiawu">
					<template #default="scope">
						<el-text :type="scope.row.xiawu_class">{{ scope.row.xiawu }}</el-text>
					</template>
				</el-table-column>

				<el-table-column v-if="logDialog.title == '加班记录'" label="加班日期" align="center" prop="xiawu">
					<template #default="scope">
						<el-text :type="scope.row.jiaban_class">{{ scope.row.jiaban_date }}</el-text>
					</template>
				</el-table-column>

				<el-table-column v-if="logDialog.title == '加班记录'" label="加班时长" align="center" prop="xiawu">
					<template #default="scope">
						<el-text :type="scope.row.jiaban_class">{{ scope.row.jiaban_time }}</el-text>
					</template>
				</el-table-column>

			</el-table>
		</el-dialog>

		<!-- 导入弹框 -->
		<el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @close="closeDialog">
			<el-form label-width="80px">
				<el-form-item label="Excel">
					<el-upload ref="upload" class="upload-demo" action="" drag show-file-list :auto-upload="false"
										 accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
										 :on-change="handleExcelChange" :on-exceed="handleExceed" :limit="1">
						<el-icon class="el-icon--upload">
							<i-ep-upload-filled />
						</el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>

						<template #tip>
							<div class="el-upload__tip">xls/xlsx files</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleKaoqinImport">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>



<script setup lang="ts">


defineOptions({
	name: "Kaoqin",
	inheritAttrs: false,
});



import {useRoute} from 'vue-router';

import {
	getKaoqin,
	importKaoqin,
} from "@/api/kaoqin";

import {getExDepartmentOptions} from "@/api/publicApi";

import { useUserStore } from "@/store/modules/user";  
import { useTableFilterStore } from "@/store/modules/tableFilter";
import { useBaseConfigStore } from "@/store/modules/baseConfig";
import {KaoqinQuery, KaoqinData} from "@/api/dangwei/types";
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
const userStore = useUserStore();
const TableFilter = useTableFilterStore();
const baseConfigStore = useBaseConfigStore();
const strtype =ref('kaoqin');

// 表格标题
	const cTitles = ["姓名","所属公司","所属部门","出勤","事假","病假","年假","旷工","加班"];
	// 显示字段
	const sTitles = ["姓名",'出勤','事假','病假','年假','旷工','加班'];
	// 字段属性
	const cColumns = [
	  { label: "姓名",prop:"name",align:"center",minwidth:100 },
	  { label: "所属公司",prop:"company",align:"center",minwidth:180 },
	  { label: "所属部门", prop:"department",align:"center",minwidth:180 },
	  { label: "出勤",prop:"chuqin",align:"center",minwidth:80 },
	  { label: "事假",prop:"shijia",align:"center",minwidth:80 },
	  { label: "病假",prop:"bingjia",align:"center",minwidth:80 },
	  { label: "年假",prop:"nianjia",align:"center",minwidth:80 },
	  { label: "旷工",prop:"kuanggong",align:"center",minwidth:80 },
	  { label: "加班",prop:"jiaban",align:"center",minwidth:80 },
	]
	
	interface TableGlobalLocal {
	  [key: string]: any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList(){
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if(ColumnsList)
		{
			const columnMap:any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {  
				columnMap[column.label] = column;  
			}  
			const newList = [];  
			for (const label of ColumnsList) {  
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];  
				if (foundColumn) {  
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);  
				}  
			}  
			return newList;  
		}
		else
		{
				return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
	  const dropColStr:string =strtype.value + '_dropCol';
	  const checklistStr:string = strtype.value + '_checklist';
	  const drop_col:any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
	  const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr]; 
	  if(!drop_col)
	  {
		  (TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr]=JSON.parse(JSON.stringify(cTitles));
		  (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr]=JSON.parse(JSON.stringify(cTitles));
	  }
	  if(!checklist)
	  {
		  (TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr]=JSON.parse(JSON.stringify(sTitles)) ;
		  (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr]=JSON.parse(JSON.stringify(sTitles));
	  }
	}
	


const now = new Date();
const lastyear = now.getFullYear() - 1;
const year = now.getFullYear();
const month = now.getMonth();
const shortcuts = [
	{
		text: '本月',
		value: () => {
			const start = new Date(year, month, 1);
			const end = new Date(year, month + 1, 0);
			return [start.toDateString(), end.toDateString()]
		},
	},
	{
		text: '上月',
		value: () => {
			const start = new Date(year, month - 1, 1);
			const end = new Date(year, month, 0);
			return [start, end]
		},
	},
	{
		text: '本季度',
		value: () => {
			const quarter = Math.floor(month / 3) + 1;
			const start = new Date(year, (quarter - 1) * 3, 1);
			const end = new Date(year, quarter * 3, 0);
			return [start, end]
		},
	},
	{
		text: '上季度',
		value: () => {
			const quarter = Math.floor(month / 3);
			const start = new Date(year, (quarter - 1) * 3, 1);
			const end = new Date(year, quarter * 3, 0);
			return [start, end]
		},
	},
	{
		text: '今年',
		value: () => {
			const start = new Date(year, 0, 1);
			const end = new Date(year, 11, 31);
			return [start, end]
		},
	},
	{
		text: '去年',
		value: () => {
			const start = new Date(lastyear, 0, 1);
			const end = new Date(lastyear, 11, 31);
			return [start, end]
		},
	},
]

const departmentOptions = ref([])

const queryFormRef = ref<any>();
const loading = ref(false);
const tableData = ref<KaoqinData[]>();
const logList = ref<any>([]);
const dialog = reactive<DialogOption>({
	title: "导入考勤",
	visible: false,
});
const logDialog = reactive<DialogOption>({
	visible: false,
});

const dateStart =new Date(year, month, 1);
const dateEnd = new Date(year, month + 1, 0);

// 时间 转化  年月日转化为 YY-MM-DD
function timeRetu(date){
	return  date.getFullYear() + '-' +  
            ('0' + (date.getMonth() + 1)).slice(-2) + '-' +  
           ('0' + date.getDate()).slice(-2); 
}

const queryParams = reactive({
		date: [timeRetu(dateStart),timeRetu(dateEnd) ], //开始时间
		department_id: "", //部门
		company_id:  "", //公司
		name: "", //姓名
		otherid:""
});

const excelFile = ref<any>([]);


/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	getKaoqin(queryParams)
			.then(({data}) => {
				tableData.value = data;
			})
			.finally(() => {
				loading.value = false;
			});
}

/**
 * 重置查询
 */
function resetQuery() {
	queryFormRef.value?.resetFields();
	handleQuery();
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	excelFile.value = undefined;
	upload.value!.clearFiles()
}

/**
 * 下载导入模板
 */
function downloadTemplate() {

	const a = document.createElement("a");
	a.href = import.meta.env.VITE_APP_BASE_API + "/kaoqin.xlsx";
	a.download = "考勤模板"
	document.body.appendChild(a);
	a.click(); // 点击下载
	document.body.removeChild(a); // 下载完成移除元素
}

/**
 * 打开导入弹窗
 */
function openImportDialog() {
	dialog.visible = true;
}

/**
 * 表单提交
 */
function handleKaoqinImport() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}

	importKaoqin(excelFile.value).then((response) => {
		ElMessage.success(response.data);
		closeDialog();
		resetQuery();
	});

}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: any) {
	if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
		ElMessage.warning("上传Excel只能为xlsx、xls格式");
		excelFile.value = undefined;
		return false;
	}
	excelFile.value = file.raw;
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles()
	const file = files[0] as UploadRawFile
	upload.value!.handleStart(file)
}

function companyChange(data, node){
	
	console.log(data);
	if(data.type == 1)
	{
		queryParams.company_id =data.id;
		queryParams.department_id = "";
		
	}
	else
	{
		queryParams.company_id = ""
		queryParams.department_id = data.id;
	}
	// return false;
	// getExDepartmentOptions({pid:data.id})
	// .then(({data}) => {
	// 	departmentOptions.value = data;
	// 	queryParams.department_id= ""
	// })
}

/**
 * 查看考勤详情
 * @param type
 * @param log
 */
function showLog(type, log){

	//循环log，log.time_result==type,list
	let list = []
	for(let key in log){
		if(log[key]['shangwu_type'] == type || log[key]['xiawu_type'] == type  || log[key]['jiaban_type'] == type || (type == 1 && (log[key]['shangwu_type'] in [2,3,5] || log[key]['xiawu_type'] in [2,3,5]))){
			list.push(log[key])
		}
	}

	logList.value = list
	logDialog.visible = true;
	if(type == 1){
		logDialog.title = '出勤记录';
	}else if(type == 2){
		logDialog.title = '早退记录';
	}else if(type == 3){
		logDialog.title = '迟到记录';
	}else if(type == 4){
		logDialog.title = '旷工记录';
	}else if(type == 5){
		logDialog.title = '忘打卡记录';
	}else if(type == 6){
		logDialog.title = '病假记录';
	}else if(type == 7){
		logDialog.title = '事假记录';
	}else if(type == 8){
		logDialog.title = '年假记录';
	}else if(type == 9){
		logDialog.title = '加班记录';
	}
}

/**
 * 关闭考勤弹窗
 */
function closeLogDialog() {
	logDialog.visible = false;
}
const showMore = ref(false);
function filterMore() {
  showMore.value = !showMore.value
}
onMounted(() => {

	handleQuery();
	columnsInit();
});
</script>
